import {BASE_URL} from "../constant/index";

export function backHandler() {
    const pages = getCurrentPages()
    console.log(pages, 'pages')
    if (pages.length > 1) {
        return wx.navigateBack()
    }
    wx.switchTab({
        url: '/pages/index/index'
    })
}

export function toast({title, time = 2000, icon = 'none'}, ...arg) {
    if (!title) return
    wx.showToast({
        title,
        icon,
        duration: time
    })
    const [callback] = arg
    if (!!callback) {
        let timeID = setTimeout(() => {
            clearTimeout(timeID)
            timeID = null
            callback()
        }, time)
    }
}

export function wxPay(options) {
    return new Promise(resolve => {
        wx.requestPayment({
            ...options,
            success: () => {
                resolve([null, true])
            },
            fail: error => {
                resolve([error, null])
            }
        })
    })

}


/**
 * 让loading多转一会
 * @param time 延迟时间
 */
export function delay(time = 300) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve()
        }, time)
    })
}


function checkUrl(url) {
    if (typeof url !== 'string') return 'url must be a [String string]!'
    if (!url || !url.length) return 'url is required!'
    return false
}

function checkHeader(header) {
    if (typeof header !== 'object') return 'Header must be a [Object object]!'
    return false
}

function getToken() {
    return wx.getStorageSync('token')
}

export function request({url, method = "POST", data = {}, header = {}}) {
    const validate = checkUrl(url)
    if (validate) return Promise.reject(new Error(validate))
    const headerValidate = checkHeader(header)
    if (headerValidate) return Promise.reject(new Error(headerValidate))
    data.token = getToken()
    return new Promise((resolve, reject) => {
        const reqUrl = BASE_URL + '/api' + url
        wx.request({
            url: reqUrl,
            data,
            method,
            header: {
                'content-type': 'application/json',
                ...header,
            },
            success: ev => {
                const {statusCode, data} = ev
                if (statusCode !== 200) return reject(data)
                return resolve(data)
            },
            fail: error => reject(error)
        })
    })

}

export function randomStr(length = 16) {
    const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let result = '';
    for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}

